package client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class C_GUI extends JLayeredPane {
	

	/* Variables */
	// GUI components
	private static JFrame chatFrame;
	private JLayeredPane layer;
	private JTextField namePane;
	private JScrollPane friendPane;
	private JButton addButton, avatarButton, messageButton, removeButton;
	
	// Back end
	private JList friendList;
	private ListModel listContents;
	private int friendIndex;
	private static C_BackEnd b;
	private String nickname, addNickname, addComputerName, addEmail;
	
	// TODO Implement statuses
	/* Statuses
	 * Online  (green)
	 * Away    (orange)
	 * Busy    (red)
	 * Offline (grey)
	 */	
	
	// Other
	private static final long serialVersionUID = 1L;	
	
	/* Main method for client */
	
	public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
	}
	
	/* Constructor */
	
	private C_GUI() {
		
		layer = this;
		
		final JPanel loginScreen = new JPanel(new GridLayout(5,1,1,1));
		
		JLabel welcome = new JLabel("Welcome to KC Chat!");
		
		JLabel login = new JLabel("Please login or register below.");
		
		final JTextArea nickname = new JTextArea();
		final JTextArea password = new JTextArea();
		
		JButton loginButton = new JButton("Login");
		loginButton.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
            	System.out.println("Logging in as "+ nickname.getText());
            	int loginResult = b.login(nickname.getText(), password.getText());
            	if (loginResult == 0) {
            		System.out.println("C_GUI --> setting login screen to Default_Layer.");
            		//layer.setLayer(loginScreen, JLayeredPane.DEFAULT_LAYER);
            		loginScreen.setVisible(false);
            		System.out.println("C_GUI --> constructing main UI (displayUI()).");
            		displayUI();
            	}
            	else if (loginResult == -2) {
            		JOptionPane.showMessageDialog(chatFrame,"Unable to contact server, cannot login.", "Logn error", JOptionPane.ERROR_MESSAGE); 
            	}
            	else {
            		JOptionPane.showMessageDialog(chatFrame,"Login failure, incorrect username/password combination.", "Logn error", JOptionPane.ERROR_MESSAGE); 
            	}
            }
        });  
		
		JButton registerButton = new JButton("Register");
		registerButton.addActionListener(new ActionListener() {
	       	 
            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
            	System.out.println("Register user");
            }
        }); 
		
		JPanel buttonPanel = new JPanel(new GridLayout(1,2,1,1));
		buttonPanel.add(loginButton);
		buttonPanel.add(registerButton);
		
		loginScreen.add(welcome);
		loginScreen.add(login);
		loginScreen.add(nickname);
		loginScreen.add(password);
		loginScreen.add(buttonPanel);
		
		loginScreen.setBounds(0,0,300,500);
		loginScreen.setVisible(true);
		
		this.add (loginScreen, JLayeredPane.POPUP_LAYER);
		setPreferredSize(new Dimension(300, 500));
		setVisible(true);
		
	}

	/* Accessors */
	
	/* Mutators */
	
	protected void setNickname (String n) {
		nickname = n;
		b.setNickname(n);
	}
	
    protected void setAddEmail(String e) {
		addEmail = e;
	}

	protected void setAddComputerName(String c) {
		addComputerName = c;
	}

	protected void setAddFriendNickname(String n) {
		addNickname = n;
	}
	
	/* Other methods */
	
    private static void createAndShowGUI() {
		b = new C_BackEnd();
    	
        //Create and set up the window.
        JFrame frame = new JFrame("KC Chat");
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame.addWindowListener( new WindowAdapter() {
        	public void windowClosing(WindowEvent e) {
        		JFrame frame = (JFrame)e.getSource();

        		int result = JOptionPane.showConfirmDialog(
        				frame,
        				"Are you sure you want to exit the application?",
        				"Exit Application",
        				JOptionPane.YES_NO_OPTION);

        		if (result == JOptionPane.YES_OPTION) {
        			try {
        				if (b.getSocket() != null) {
        					b.getSocket().close();
        				}
        			} 
        			catch (IOException e1) {
        				System.out.println("C_GUI ("+b.getNickname()+") -> couldn't close the socket.");
        				e1.printStackTrace();
        			}
        			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        		}
        	}
        });

        //Create and set up the content pane.
        JLayeredPane newContentPane = new C_GUI();
        frame.setContentPane(newContentPane);
        
        BufferedImage icon = null;
		try {
			icon = ImageIO.read(new File("window.png"));
			frame.setIconImage(icon);
		} 
		catch (IOException e) {
			System.out.println("C_GUI ("+b.getNickname()+") -> Couldn't find frame icon!");
			e.printStackTrace();
		}
        
        //Display the window.
        frame.pack();
        frame.setVisible(true);
        chatFrame = frame;
    }
    
    /* GUI actions */
    
	private void changeNickname(String newNickname) {
		setNickname(newNickname);
	}
	
	private void changeAvatar() {
		final JDialog dialog = new JDialog(chatFrame);
		JFileChooser imageBrowser = new JFileChooser("./Avatars/");
		dialog.setBounds(0,0,600,400);
		dialog.add(imageBrowser);
		dialog.setVisible(true);
		
		// Add listener for approve and cancel events
		imageBrowser.addActionListener(new AbstractAction() {
		    
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent evt) {
		        JFileChooser chooser = (JFileChooser)evt.getSource();
		        if (JFileChooser.APPROVE_SELECTION.equals(evt.getActionCommand())) {
		            // Open or Save was clicked
		        	File newAvatar = chooser.getSelectedFile();
		        	System.out.println(newAvatar.getPath());
		    		
		    		avatarButton.setIcon(new ImageIcon(newAvatar.getPath()));
		            // Hide dialog
		            dialog.setVisible(false);
		        } else if (JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) {
		            // Cancel was clicked

		            // Hide dialog
		            dialog.setVisible(false);
		        }
		    }
		});

		// Add listener for window closing events
		dialog.addWindowListener(new WindowAdapter() {
		    public void windowClosing(WindowEvent e) {
		        // Close-dialog icon was clicked

		        // Hide dialog
		        dialog.setVisible(false);
		    }
		});
	}
    
	private void displayUI() {
		
		b.startThread();
		
		//Top
		//avatarNamePanel
		JPanel avatarNamePanel = new JPanel();
		SpringLayout layoutTop = new SpringLayout();
		avatarNamePanel.setLayout(layoutTop);

		avatarButton = new JButton();
		avatarButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//Execute when button is pressed
				System.out.println("Change avatar");
				changeAvatar();
			}
		}); 
		avatarButton.setBorder(new LineBorder(Color.green, 1));
		ImageIcon icon = new ImageIcon("Avatars/avatar.png");
		avatarButton.setIcon(icon); // TODO get avatar from server
		Dimension size = new Dimension(icon.getIconHeight(), icon.getIconWidth());
		avatarButton.setSize(size);

		nickname=b.getNickname();
		namePane = new JTextField(nickname);
		namePane.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				JTextField textField = (JTextField) e.getSource();
				String newNickname = textField.getText();

				System.out.println("Changing nickname to "+ newNickname);
				changeNickname(newNickname);
			}
		}); 

		avatarNamePanel.add(avatarButton);
		avatarNamePanel.add(namePane);

		layoutTop.putConstraint(SpringLayout.WEST, avatarButton, 5, SpringLayout.WEST, avatarNamePanel);
		layoutTop.putConstraint(SpringLayout.NORTH, avatarButton, 5, SpringLayout.NORTH, avatarNamePanel);
		layoutTop.putConstraint(SpringLayout.SOUTH, avatarButton, 5, SpringLayout.SOUTH, avatarNamePanel);

		layoutTop.putConstraint(SpringLayout.WEST, namePane, 5, SpringLayout.EAST, avatarButton);
		layoutTop.putConstraint(SpringLayout.NORTH, namePane, 5, SpringLayout.NORTH, avatarNamePanel);
		layoutTop.putConstraint(SpringLayout.EAST, avatarNamePanel, 5, SpringLayout.EAST, namePane);
		layoutTop.putConstraint(SpringLayout.SOUTH, avatarNamePanel, 1, SpringLayout.SOUTH, namePane);

		//friendTitle

		JTextField friendTitle = new JTextField("Friend List");
		friendTitle.setEditable(false);

		//splitTop
		JPanel splitTop = new JPanel(new GridLayout(2,1,1,1));

		splitTop.add(avatarNamePanel);
		splitTop.add(friendTitle);

		//friendPane		
		//String[] friends = {"Michael", "Neil"};
		String[] friends = b.getFriendsString();
		for (int i = 0; i <friends.length; i++) {
			System.out.println(friends[i]);
		}

		friendList = new JList(friends);
		listContents = friendList.getModel();
		MouseListener mouseListener = new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					friendIndex = friendList.locationToIndex(e.getPoint());
					System.out.println("Double clicked on Item " + friendIndex);
					messagePrompt(friendIndex);
				}
				else if (e.getClickCount() == 1){
					friendIndex = friendList.locationToIndex(e.getPoint());
					System.out.println("Single clicked on Item " + friendIndex);
				}
			}
			public void mouseEntered(MouseEvent e) {				
			}
			public void mouseExited(MouseEvent e) {				
			}
			public void mousePressed(MouseEvent e) {		
			}
			public void mouseReleased(MouseEvent e) {				
			}
		};
		friendList.addMouseListener(mouseListener);

		friendPane = new JScrollPane(friendList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		//Split
		JSplitPane top = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splitTop, friendPane);
		top.setDividerSize(0);

		//Bottom

		JPanel bottom = new JPanel();
		bottom.setLayout(new BorderLayout());

		addButton = new JButton("Add");		
		addButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//Execute when button is pressed
				System.out.println("Add a friend");
				addFriend();
			}
		});   

		messageButton = new JButton("Message");
		messageButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//Execute when button is pressed
				System.out.println("Send a message");
				messagePrompt(friendIndex);
			}
		});   

		removeButton = new JButton("Remove");        
		removeButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				//Execute when button is pressed
				System.out.println("Removing friend");
				removeFriend(friendIndex);
			}
		});   

		JPanel borderPanel = new JPanel();
		borderPanel.add(addButton);
		borderPanel.add(messageButton);
		borderPanel.add(removeButton);

		addButton.setPreferredSize(new Dimension(80,30));
		messageButton.setPreferredSize(new Dimension(100,30));
		removeButton.setPreferredSize(new Dimension(80,30));		

		bottom.add(borderPanel);

		//Root

		JPanel root = new JPanel();
		BorderLayout layoutRoot = new BorderLayout();
		root.setLayout(layoutRoot);

		root.add(top, BorderLayout.CENTER);
		root.add(bottom, BorderLayout.SOUTH);

		SpringLayout layoutLayer = new SpringLayout();
		this.setLayout(layoutLayer);
		add(root,JLayeredPane.DRAG_LAYER);

		layoutLayer.putConstraint(SpringLayout.WEST, root, 1, SpringLayout.WEST, this);
		layoutLayer.putConstraint(SpringLayout.NORTH, root, 1, SpringLayout.NORTH, this);
		layoutLayer.putConstraint(SpringLayout.EAST, root, 1, SpringLayout.EAST, this);
		layoutLayer.putConstraint(SpringLayout.SOUTH, root, 1, SpringLayout.SOUTH, this);
		
		root.setBounds(0,0,300,500);
		root.setVisible(true);

	}
	
    private void addFriend () {
    	
    	// DEPRECATED relative positioning for the "Add Friend" dialog.
    	// DEPRECATED distinguish between adding a current user and a new user.
    	
    	final JDialog dialog = new JDialog(chatFrame);
    	dialog.setTitle("Add a friend");
    	JPanel addFriendPanel = new JPanel();
    	addFriendPanel.setLayout(new BorderLayout());
    	
    	// DEPRECATED a way to handle transition from usersMinusCurrent to friends int arrays?
    	// DEPRECATED add ItemListenner here for selections on the JComboBox to tie into the addFriend method.
/*	    String[] users = b.serverB.getUsernames();
	    String[] usersMinusCurrent = new String[users.length-1];
	    int i = 0, j = 0;
	    while (i < users.length) {
	    	if (!(users[i].compareTo(nickname)==0)) {
	    		usersMinusCurrent[j] = users[i];
	    		j++;
	    	}
	    	i++;
	    }*/
    	
    	//JComboBox userDropDown = new JComboBox(usersMinusCurrent);
    	
    	JLabel computerNameLabel = new JLabel("Computer");
    	JTextField computerNameField = new JTextField("Computer");
    	computerNameField.addKeyListener(new KeyAdapter() {
			
            public void keyReleased(KeyEvent e) {
                JTextField textField = (JTextField) e.getSource();
                String computerName = textField.getText();
                
                System.out.println("Nickname set to "+ computerName);
                setAddComputerName(computerName);
            }
        }); 
    	JPanel computerNamePanel = new JPanel();
    	SpringLayout computerNameLayout = new SpringLayout();
    	computerNamePanel.setLayout(computerNameLayout);
    	
    	computerNamePanel.add(computerNameLabel);
    	computerNamePanel.add(computerNameField);
		
    	computerNameLayout.putConstraint(SpringLayout.WEST, computerNameLabel, 5, SpringLayout.WEST, computerNamePanel);
    	computerNameLayout.putConstraint(SpringLayout.NORTH, computerNameLabel, 5, SpringLayout.NORTH, computerNamePanel);
    	computerNameLayout.putConstraint(SpringLayout.SOUTH, computerNameLabel, 5, SpringLayout.SOUTH, computerNamePanel);
		
    	computerNameLayout.putConstraint(SpringLayout.WEST, computerNameField, 5, SpringLayout.EAST, computerNameLabel);
    	computerNameLayout.putConstraint(SpringLayout.NORTH, computerNameField, 5, SpringLayout.NORTH, computerNamePanel);
    	computerNameLayout.putConstraint(SpringLayout.EAST, computerNamePanel, 5, SpringLayout.EAST, computerNameField);
    	computerNameLayout.putConstraint(SpringLayout.SOUTH, computerNamePanel, 5, SpringLayout.SOUTH, computerNameField);
    	
    	JLabel nicknameLabel = new JLabel("Name");
    	JTextField nicknameField = new JTextField("Name");
    	nicknameField.addKeyListener(new KeyAdapter() {
			
            public void keyReleased(KeyEvent e) {
                JTextField textField = (JTextField) e.getSource();
                String nickname = textField.getText();
                
                System.out.println("Computer name set to "+ nickname);
                setAddFriendNickname(nickname);
            }
        }); 
    	JPanel nicknamePanel = new JPanel();
    	SpringLayout nicknameLayout = new SpringLayout();
    	nicknamePanel.setLayout(nicknameLayout);
    	
    	nicknamePanel.add(nicknameLabel);
    	nicknamePanel.add(nicknameField);
		
    	nicknameLayout.putConstraint(SpringLayout.WEST, nicknameLabel, 5, SpringLayout.WEST, nicknamePanel);
    	nicknameLayout.putConstraint(SpringLayout.NORTH, nicknameLabel, 5, SpringLayout.NORTH, nicknamePanel);
    	nicknameLayout.putConstraint(SpringLayout.SOUTH, nicknameLabel, 5, SpringLayout.SOUTH, nicknamePanel);
		
    	nicknameLayout.putConstraint(SpringLayout.WEST, nicknameField, 5, SpringLayout.EAST, computerNameLabel);
		nicknameLayout.putConstraint(SpringLayout.NORTH, nicknameField, 5, SpringLayout.NORTH, nicknamePanel);
		nicknameLayout.putConstraint(SpringLayout.EAST, nicknamePanel, 5, SpringLayout.EAST, nicknameField);
		nicknameLayout.putConstraint(SpringLayout.SOUTH, nicknamePanel, 5, SpringLayout.SOUTH, nicknameField);
    	
    	JLabel emailLabel = new JLabel("Email");
    	JTextField emailField = new JTextField("Email");
    	emailField.addKeyListener(new KeyAdapter() {
			
            public void keyReleased(KeyEvent e) {
                JTextField textField = (JTextField) e.getSource();
                String email = textField.getText();
                
                System.out.println("Email set to "+ email);
                setAddEmail(email);
            }
        }); 
    	JPanel emailPanel = new JPanel();
    	SpringLayout emailLayout = new SpringLayout();
    	emailPanel.setLayout(emailLayout);
    	
    	emailPanel.add(emailLabel);
    	emailPanel.add(emailField);
		
    	emailLayout.putConstraint(SpringLayout.WEST, emailLabel, 5, SpringLayout.WEST, emailPanel);
    	emailLayout.putConstraint(SpringLayout.NORTH, emailLabel, 5, SpringLayout.NORTH, emailPanel);
    	emailLayout.putConstraint(SpringLayout.SOUTH, emailLabel, 5, SpringLayout.SOUTH, emailPanel);
		
    	emailLayout.putConstraint(SpringLayout.WEST, emailField, 5, SpringLayout.EAST, computerNameLabel);
    	emailLayout.putConstraint(SpringLayout.NORTH, emailField, 5, SpringLayout.NORTH, emailPanel);
    	emailLayout.putConstraint(SpringLayout.EAST, emailPanel, 5, SpringLayout.EAST, emailField);
    	emailLayout.putConstraint(SpringLayout.SOUTH, emailPanel, 5, SpringLayout.SOUTH, emailField);
    	
    	JButton addButton = new JButton("Add friend");
		addButton.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                System.out.println("Add friend");
                // DEPRECATED add if statements to test whether the text boxes or the combo box was used, i.e. new or current user and filter to the appropriate addFriend method.
                b.addFriend(addNickname, addComputerName, addEmail);
                updateFriends(b.getFriends().size()+1, b.serverB.users); // DEPRECATED update to new friend list spec
                dialog.setVisible(false);
            }
        }); 
		
    	JButton cancelButton = new JButton("Cancel");
    	cancelButton.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                System.out.println("Cancel adding a friend");
                dialog.setVisible(false);
            }
        }); 
    	JPanel top = new JPanel(new GridLayout(4,1,1,1));
    	//top.add(userDropDown);
    	top.add(nicknamePanel);
    	top.add(computerNamePanel);
    	top.add(emailPanel);
    	
    	JPanel buttonPanel = new JPanel();
    	buttonPanel.add(addButton);
    	buttonPanel.add(cancelButton);
    	
    	JTextArea speil = new JTextArea("To add a friend fill in at least one of the fields below and press the 'Add friend' button to continue.");

    	addFriendPanel.add(top, BorderLayout.CENTER);
    	addFriendPanel.add(buttonPanel, BorderLayout.SOUTH);
    	
		JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, speil, addFriendPanel);
		split.setDividerSize(0);
    	
    	dialog.getContentPane().add(split);
    	dialog.setBounds(0,0,200,300);
    	dialog.setVisible(true);
    	System.out.println("Add friend dialog visible");
    }

	private void messagePrompt (final int i) {
		
    	// TODO relative positioning for the "Message Prompt" dialog.
    	
    	final JDialog dialog = new JDialog(chatFrame);
    	
    	String name = b.getFriendsString()[0];
    	
    	dialog.setTitle("Conversation with "+ name);
    	JPanel messagePromptPanel = new JPanel();
    	messagePromptPanel.setLayout(new BorderLayout());
    	
    	final JEditorPane editorPane = new JEditorPane();;
    	b.getTextPanes().put(i, editorPane);
      	
    	editorPane.setEditable(false);
    	JScrollPane scroller = new JScrollPane(editorPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    	scroller.setPreferredSize(new Dimension(200,200));
    	
    	final JEditorPane textEntry = new JEditorPane();
    	textEntry.addKeyListener(new KeyAdapter() {
			
            public void keyReleased(KeyEvent e) {
                JEditorPane editorPane = (JEditorPane) e.getSource();
                String enteredText = editorPane.getText();
                
                System.out.println("Text entry set to "+ enteredText);
                //setAddEnteredText(enteredText);
            }
        }); 
    	JScrollPane scrollerEntry = new JScrollPane(textEntry, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    	JButton sendButton = new JButton("Send");
    	sendButton.addActionListener(new ActionListener() {
          	 
            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                System.out.println("Send message");
                String message = textEntry.getText();
                textEntry.setText("");
                editorPane.setText(editorPane.getText()+"Me: "+message+"\n");
                
                sendMessage(editorPane, message, b.getFriendsString()[friendIndex]);
            }
        }); 
    	
    	JPanel bottom = new JPanel(new BorderLayout());
    	bottom.add(scrollerEntry, BorderLayout.CENTER);
    	bottom.add(sendButton, BorderLayout.EAST);

		JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scroller, bottom);
		split.setDividerLocation(500);
		split.setDividerSize(2);

    	dialog.getContentPane().add(split);
    	dialog.setBounds(0,0,400,600);
    	dialog.setVisible(true);
    	System.out.println("Message prompt dialog visible");
    }

	private void removeFriend(int i) {
		
    	ArrayList<String[]> u = b.serverB.users;
    	
    	int index = findIndexFromFriendList(i, u);
    	if (index != -1) {
    		updateFriends(index, u);
    	}
		
    }
    
    private void sendMessage(JEditorPane e, String message, String reciepient) {

    	b.sendMessage(e, message, reciepient);
    	
    }
    
    /* Helper methods */
    
/*    private int findIndexFromFriendList (int i) {
    	ArrayList<String[]> u = b.serverB.getUsers();
    	
    	if (b.noOfFriends > 0) {
    		int k = 0;
			int index = -1;
			String name = null;
			String[] f = b.getFriendsString();
			int listLength = f.length;
			while (k < listLength) {
				if (k == i) {
					name = b.getFriendsString()[k];
				}
				k++;
			}
			for (int l = 0; l < u.size(); l++) {
				System.out.println(u.get(l)[0]);
				if (u.get(l)[0].compareTo(name) == 0) {
					index = l;
				}
			}
			return index;
    	}
    	return -1;
    }*/
    
    private int findIndexFromFriendList (int i, ArrayList<String[]> u) {
    	
    	if (b.noOfFriends > 0) {
    		int k = 0;
			int index = -1;
			String name = null;
			String[] f = b.getFriendsString();
			int listLength = f.length;
			while (k < listLength) {
				if (k == i) {
					name = b.getFriendsString()[k];
				}
				k++;
			}
			for (int l = 0; l < u.size(); l++) {
				System.out.println(u.get(l)[0]);
				if (u.get(l)[0].compareTo(name) == 0) {
					index = l;
				}
			}
			return index;
    	}
    	return -1;
    }
    
	protected static String friendRequest(String segment2) {

		if (JOptionPane.showConfirmDialog(chatFrame,segment2+ " wants to add you as a friend. Do you accept?", "Friend request", JOptionPane.YES_NO_OPTION) == 0) {
			return "acceptFriendRequest";
		}
		else {
			return "declineFriendRequest";
		}
		
	}
    
    /**
     * 
     * (Deprecated)
     * @param i
     * @return
     */
    private String findStringFromIntFriend (int i) {
    	
    	if (b.noOfFriends > 0) {
    		int k = 0;
			String name = null;
			String[] f = b.getFriendsString();
			int listLength = f.length;
			while (k < listLength) {
				if (k == i) {
					name = b.getFriendsString()[k];
				}
				k++;
			}

			return name;
    	}
    	return null;
    }
    
    /**
     * 
     * (Deprecated)
     * @param i
     * @param u
     */
    private void updateFriends (int i, ArrayList<String[]> u) {
    	System.out.println("Entered updateFriends");
		DefaultListModel listModel = new DefaultListModel();
		System.out.println(b.friends.size());
		for (int j = 0; j < b.friends.size(); j++) {
			System.out.println(j);
			System.out.println(b.friends.get(j));
    				listModel.addElement(u.get(j)[0]);

		}
    	System.out.println("calling within updateFriends");
		//b.updateFriendsList(newFriends, b.index); // DEPRECATED update to new friend list spec
		friendList.setModel(listModel);
		b.noOfFriends--;
    }
}